import React, { useState } from 'react';
import { View, TextInput, Button, Pressable, Text, StyleSheet } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import axios from 'axios';
import Toast from 'react-native-toast-message';
import AsyncStorage from '@react-native-async-storage/async-storage';

export default function RegisterScreen() {
  const [phone, setPhone] = useState('');
  const [userCode, setUserCode] = useState('');
  const [serverCode, setServerCode] = useState(''); // 新增状态变量
  const navigation = useNavigation();
  const sendCode = () => {
    console.log(`手机号: ${phone}`);
    axios.post('http://47.111.227.58:3000/login/code', {
      data: {
        phone: phone
      }
    })
      .then(function (res) {
        console.log(res.data);
        setServerCode(JSON.parse(res.data.data.data)); // 存储从服务器获取的验证码
        Toast.show({
          type: 'success',
          text1: '验证码为：'+JSON.parse(res.data.data.data),
        });
      })
      .catch(function (error) {
        console.log(error);
      });
  };

  const register = () => {
    if(userCode==='') {
      Toast.show({
          type: 'error',
          text1: '请输入验证码',
      });
      return;
  }
    console.log(`手机号: ${phone}\n验证码: ${userCode}`);
    if (Number(userCode) !== Number(serverCode)) { // 比较用户输入的验证码和从服务器获取的验证码
      Toast.show({
        type: 'error',
        text1: '验证码错误',
      });
      return; // 如果验证码不匹配，阻止跳转
    }
    axios.post('http://47.111.227.58:3000/login/addUser', {
      data: {
        phone: phone
      }
    })
      .then(function (res) {
        console.log(res.data);
        AsyncStorage.setItem('userInfo', JSON.stringify(res.data.data.data));
        AsyncStorage.setItem('token', res.data.data.data.token);
        AsyncStorage.setItem('name',JSON.stringify(res.data.data.data.username));
        AsyncStorage.setItem('loginStatus',true);
        Toast.show({
          type: 'success',
          text1: '注册成功',
        });
        navigation.navigate('Login');
      })
      .catch(function (error) {
        console.log(error);
      });
  };

  return (
    <View style={{ flex: 1, justifyContent: 'center', padding: 16, backgroundColor: '#FFF' }}>
      <TextInput
        style={{ height: 40, borderColor: '#808080', borderWidth: 1, marginBottom: 16, borderRadius: 5, paddingLeft: 10 }}
        onChangeText={setPhone}
        value={phone}
        placeholder="请输入手机号"
      />
      <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginBottom: 16 }}>
        <TextInput
          style={{ height: 40, borderColor: '#808080', borderWidth: 1, flex: 1, marginRight: 16, borderRadius: 5, paddingLeft: 10 }}
          onChangeText={setUserCode}
          value={userCode}
          placeholder="请输入验证码"
        />
        <Button
          title="获取验证码"
          onPress={sendCode}
          color="#EB7A76"
        />
      </View>
      <Button
        title="下一步"
        onPress={register}
        color="#EB7A76"
      />
      <Pressable onPress={() => navigation.navigate('Login')}>
        <Text style={{ color: '#EB7A76' }}>密码登录</Text>
      </Pressable>
    </View>
  );
}
